package com.FengChaoSystem.untils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用于过滤敏感词
 */
public class DFASensitiveWordFilter  {
    private static class TrieNode {
        Map<Character, TrieNode> children = new HashMap<>();
        boolean isEndOfWord;
    }

    private TrieNode root = new TrieNode();

    // 添加敏感词到敏感词树
    public void addSensitiveWord(String word) {
        TrieNode current = root;
        for (char ch : word.toCharArray()) {
            current = current.children.computeIfAbsent(ch, c -> new TrieNode());
        }
        current.isEndOfWord = true;
    }

    // 构建敏感词树
    public void buildSensitiveWordTree(List<String> sensitiveWords) {
        for (String word : sensitiveWords) {
            addSensitiveWord(word);
        }
    }

    // 过滤文本中的敏感词
    public String filter(String text) {
        StringBuilder result = new StringBuilder();
        TrieNode current;

        for (int i = 0; i < text.length(); i++) {
            char ch = text.charAt(i);
            current = root;

            // 查找以当前字符开头的敏感词
            int j = i;
            while (current.children.containsKey(ch)) {
                current = current.children.get(ch);
                if (current.isEndOfWord) {
                    // 发现敏感词，将其替换为***
                    result.append("***");
                    break;
                }
                if (++j >= text.length()) break;
                ch = text.charAt(j);
            }

            // 如果没有发现敏感词，则将当前字符加入结果中
            if (!current.isEndOfWord) {
                result.append(text.charAt(i));
            } else {
                i = j;
            }
        }

        return result.toString();
    }




}
